package com.six.security.aspect;

import com.six.core.util.JwtUtil;
import com.six.core.util.WebUtil;
import com.six.security.annotation.HasPermission;
import com.six.security.exception.PermissionException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @author: WangPeng
 * @createTime: 2023/02/27 11:48
 * @description:
 * @version: v1.0
 */
@Aspect
@Component
public class PermissionAspect {
    @Pointcut(value ="@annotation(com.six.security.annotation.HasPermission)" )
    public void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        HasPermission hasPermission = method.getAnnotation(HasPermission.class);
        if (hasPermission != null){
            String permission = hasPermission.value();
            HttpServletRequest request = WebUtil.getRequest();
            String token = request.getHeader("token");
            //解析token
            Map<String, Object> map = JwtUtil.decodeJWT(token);
            List<String> authorities = (List<String>) map.get("authorities");
            if (!authorities.contains(permission)){
                throw new PermissionException("权限不足");
            }
        }
        return joinPoint.proceed();
    }


}
